package com.example.file_management.controller;

import com.example.file_management.pojo.material.Resource;
import com.example.file_management.service.ResourceService;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



@RestController
@RequestMapping("/api/resources")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class ResourceController {

    private final ResourceService resourceService;

    @Autowired
    public ResourceController(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    // 📤 上传文件（自动管理版本）
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam("taskName") String taskName) {
        if (taskName == null || taskName.isEmpty()) {
            return ResponseEntity.badRequest().body("任务名称不能为空");
        }
        String responseMessage = resourceService.uploadFile(file, taskName);
        return responseMessage.contains("成功")
                ? ResponseEntity.status(HttpStatus.CREATED).body(responseMessage)
                : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseMessage);
    }

    // 🔍 获取某任务下的所有文件（包含不同版本）
    @GetMapping("/resources")
    public ResponseEntity<List<Resource>> getResourcesByTaskName(@RequestParam(required = false) String taskName) {
        List<Resource> resources = resourceService.getResourcesByTaskName(taskName);
        return resources.isEmpty()
                ? ResponseEntity.noContent().build()
                : ResponseEntity.ok(resources);
    }

    // 🔄 获取某文件的所有版本
    @GetMapping("/versions")
    public ResponseEntity<List<String>> getFileVersions(@RequestParam String taskName, @RequestParam String fileName) {
        List<Resource> versions = resourceService.getFileVersions(taskName, fileName);
        List<String> versionStrings = versions.stream()
                .map(String::valueOf)  // 将 Integer 转换为 String
                .collect(Collectors.toList());
        return versionStrings.isEmpty()
                ? ResponseEntity.noContent().build()
                : ResponseEntity.ok(versionStrings);
    }


    // 📥 下载文件（默认最新版本，支持指定版本）
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam String taskName,
                                               @RequestParam String fileName,
                                               @RequestParam(required = false) Integer version) {
        if (taskName == null || fileName == null || taskName.isEmpty() || fileName.isEmpty()) {
            return ResponseEntity.badRequest().body(null);
        }
        try {
            byte[] fileContent = resourceService.downloadFile(taskName, fileName, version);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDisposition(ContentDisposition.attachment().filename(fileName).build());
            return ResponseEntity.ok().headers(headers).body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    // 🗑️ 删除文件（支持删除特定版本或所有版本）
    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteFile(@RequestParam String taskName,
                                             @RequestParam String fileName,
                                             @RequestParam(required = false) Integer version) {
        if (taskName == null || fileName == null || taskName.isEmpty() || fileName.isEmpty()) {
            return ResponseEntity.badRequest().body("任务名和文件名不能为空");
        }
        boolean isDeleted = resourceService.deleteFile(taskName, fileName, version);
        return isDeleted
                ? ResponseEntity.ok("文件删除成功")
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件未找到，删除失败");
    }

    // ⏳ 版本回滚
    @PostMapping("/rollback")
    public ResponseEntity<String> rollbackFile(@RequestParam String taskName,
                                               @RequestParam String fileName,
                                               @RequestParam int targetVersion) {
        if (taskName == null || fileName == null || taskName.isEmpty() || fileName.isEmpty()) {
            return ResponseEntity.badRequest().body("任务名和文件名不能为空");
        }
        boolean isRolledBack = resourceService.rollbackFileVersion(taskName, fileName, targetVersion);
        return isRolledBack
                ? ResponseEntity.ok("文件已成功回滚到版本 " + targetVersion)
                : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("回滚失败");
    }

    // 📄 预览文件（默认使用最新版本）
    @GetMapping("/preview")
    public ResponseEntity<Object> previewFile(@RequestParam String taskName, @RequestParam String fileName) {
        if (taskName == null || fileName == null || taskName.isEmpty() || fileName.isEmpty()) {
            return ResponseEntity.badRequest().body("任务名和文件名不能为空");
        }
        try {
            File pdfFile = resourceService.previewFile(taskName, fileName);
            if (!pdfFile.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            return ResponseEntity.ok().headers(headers).body(new InputStreamResource(new FileInputStream(pdfFile)));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    @GetMapping("/storage")
    public ResponseEntity<?> getStorageInfo() {
        try {
            return ResponseEntity.ok(resourceService.getStorageInfo());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "无法获取存储信息"));
        }
    }

    @GetMapping("/file-categories")
    public List<Map<String, Object>> getFileCategories() {
        List<Map<String, Object>> fileCategories = resourceService.getFileCategories();
        return fileCategories;
    }
    @GetMapping("/search")
    public ResponseEntity<List<Resource>> getResourcesByFileName(@RequestParam String fileName) {
        try {
            List<Resource> resources = resourceService.getResourcesByFileName(fileName);
            return ResponseEntity.ok(resources);
        } catch (Exception e) {
            // 日志记录异常信息
            e.printStackTrace();
            return ResponseEntity.status(500).body(null); // 返回服务器错误状态码
        }
    }

}
